package org.example.task.controller;


import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.example.task.converter.UserRoleConverterMapper;
import org.example.task.model.dto.PageDTO;
import org.example.task.model.dto.userrole.AddDOT;
import org.example.task.model.po.UserRole;
import org.example.task.model.query.UserRolePageQuery;
import org.example.task.model.vo.R;
import org.example.task.model.vo.userrole.UserRoleVO;
import org.example.task.service.IUserRoleService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 用户角色管理接口
 *
 * @module 用户角色管理接口
 */
@RestController
@RequestMapping("/user-role")
@RequiredArgsConstructor
@Validated
public class UserRoleController {
    private final IUserRoleService userRoleService;
    private final UserRoleConverterMapper userRoleConverterMapper;

    /**
     * 查询用户角色列表
     *
     * @param userRolePageQuery 请求数据
     * @return 查询结果
     */
    @GetMapping
    public R<PageDTO<UserRoleVO>> getList(@Valid @RequestBody UserRolePageQuery userRolePageQuery) {
        PageDTO<UserRoleVO> result = userRoleService.getUserRolePage(userRolePageQuery);
        return R.success(result);
    }

    /**
     * 添加用户角色
     *
     * @param addDOT 用户和角色id
     * @return 结果
     */
    @PostMapping
    public R addUserRole(@Valid @RequestBody AddDOT addDOT) {
        UserRole userRole = userRoleConverterMapper.toEntity(addDOT);
        userRole.setCreateTime(LocalDateTime.now());
        if (userRoleService.save(userRole)) {
            return R.success();
        }
        return R.error("操作失败");
    }

    /**
     * 删除用户角色
     *
     * @param userId 用户id
     * @param roleId 角色id
     * @return 结果
     */
    @DeleteMapping
    public R deleteUserRoleById(@RequestParam @NotNull Long userId, @RequestParam @NotNull Long roleId) {
        if (userRoleService.removeUserRoleById(userId, roleId)) {
            return R.success();
        }
        return R.error("操作失败");
    }
}
